package com.jic.purchase.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.product.store.MStoreApi;
import com.jic.product.store.request.MStore;
import com.jic.product.store.request.MStoreReq;
import com.jic.purchase.constant.consist.ResponseCode;
import com.jic.purchase.exception.AppRuntimeException;
import com.jic.purchase.mapper.PurchaseContractProductRelMapper;
import com.jic.purchase.model.entity.PurchaseContractProductRel;
import com.jic.purchase.model.vo.request.PurchaseOrderRequest;
import com.jic.purchase.model.vo.response.PurchaseContractProductRelResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.jic.purchase.mapper.PurchaseContractMapper;
import com.jic.purchase.mapper.PurchaseOrderMapper;
import com.jic.purchase.model.entity.PurchaseContract;
import com.jic.purchase.model.entity.PurchaseOrder;
import com.jic.purchase.service.PurchaseOrderService;
import lombok.extern.slf4j.Slf4j;

/**
 * 接口实现类
 *
 * @author : 建投数据科技(山东)有限公司
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class PurchaseOrderServiceImpl implements PurchaseOrderService {

    private PurchaseOrderMapper mapper;
    private PurchaseContractMapper purchaseContractMapper;
    private MStoreApi mStoreApi;
    private PurchaseContractProductRelMapper productRelMapper;


    /**
     * 根据合同编号增加采购单
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存成功
     */
    @Override
    public int save(PurchaseOrder request) {
        if (!(request.getContractId() > 0)) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "合同编号不正确");
        }
        PurchaseContract contract = new PurchaseContract();
        contract.setCode(request.getContractId());
        List<PurchaseContract> contracts = purchaseContractMapper.selectBySelective(contract);
        if (!CollectionUtil.isNotEmpty(contracts)) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "合同不存在");
        }
        PurchaseOrder queryParam = new PurchaseOrder();
        queryParam.setContractId(request.getContractId());
        List<PurchaseOrder> orders = mapper.selectBySelective(queryParam);
        if (CollectionUtil.isNotEmpty(orders)) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "该合同对应采购单已存在");
        }

        //新增采购单
        PurchaseContract purchaseContract = contracts.get(0);
        //根据merchant_code商家编码查询对应实体仓
        MStoreReq req = new MStoreReq();
        req.setMerchantCode(purchaseContract.getDeptCode());
        RestResult<MStore> store = mStoreApi.getStoreByMerchantCode(req);

        request.setName(purchaseContract.getName());
        request.setDeptId(purchaseContract.getDeptId());
        request.setStoreId(purchaseContract.getDeptId());
        request.setStoreName(purchaseContract.getDeptName());
        request.setCode(RandomUtil.randomUUID());
        //TODO
//        request.setSupplierId(purchaseContract.getSupplierId());
        request.setSupplierName(purchaseContract.getSupplierName());
        request.setCreateTime(new Date());
        request.setUpdateTime(new Date());
        request.setStatus(0);//商家/店铺】暂存插表； 待提交
        request.setStoreId(store.getData().getId());
        request.setStoreName(store.getData().getName());
        request.setDeleteFlag(0);
        request.setType(1);
        //新增采购单、退货单、补货单
        int flag = mapper.insert(request);
//        request.setType(2);
//        request.setName(request.getName()+"补货单");
//         mapper.insert(request);
//        request.setType(3);
//        request.setName(request.getName()+"退货单");
//        mapper.insert(request);
        //同步修改对应合同的采购单编码
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
        }
    }


    /**
     * 保存或修改记录信息
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存或修改成功
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:09
     */
    @Override
    public int saveOrUpdate(PurchaseOrder request) {
        log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
        try {
            if (request == null) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "入参为空");
            }
            if (request.getId() != null) {
                log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.updateByPrimaryKey(request);
                if (flag == 1) {
                    return 1;
                }
            } else {
                log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.insertSelective(request);
                if (flag == 1) {
                    return 1;
                } else {
                    throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改失败");
                }
            }
        } catch (Exception e) {
            log.error("用户保存或修改失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "用户保存或修改失败");
        }
        return -1;
    }

    /**
     * 删除记录
     *
     * @param request 需要删除,含有主键的入参实体类
     * @return int 是否删除成功
     */
    @Override
    public int deleteByPrimaryKey(PurchaseOrder request) {
        int flag = mapper.deleteByPrimaryKey(request.getId());
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
        }
    }


    /**
     * 逻辑删除记录
     *
     * @param request 含有主键的逻辑删除实体类
     * @return int 是否逻辑删除成功
     */
    @Override
    public int deleteByPrimaryKeyLogically(PurchaseOrder request) {
        request.setDeleteFlag(1);
        int flag = mapper.updateByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
        }
    }


    /**
     * 修改
     *
     * @param request
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(PurchaseOrder request) {
        try {
            log.info("修改记录");
            PurchaseOrder param = new PurchaseOrder();
            BeanUtils.copyProperties(request, param);
            int flag = mapper.updateByPrimaryKeySelective(param);
            if (flag == 1) {
                return 1;
            } else {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
            }
        } catch (Exception e) {
            log.error("修改记录失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
        }

    }

    /**
     * 记录详情
     *
     * @param request 查询的入参实体类
     * @return 数据库查询到的实体类
     */
    @Override
    public PurchaseOrder getByPrimaryKey(PurchaseOrder request) {
        return mapper.selectByPrimaryKey(request.getId());
    }


    /**
     * 分页查询
     *
     * @param request 分页查询入参实体类
     * @return 含有分页信息的实体类列表
     */
    @Override
    public PageResult<PurchaseOrder> listPageBySelective(PurchaseOrder request, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        List<PurchaseOrder> list = mapper.listPageBySelective(request);
        PageInfo<PurchaseOrder> pageInfo = new PageInfo<>(list);
        PageResult<PurchaseOrder> result = new PageResult<>();
        result.setTotal(pageInfo.getTotal());
        result.setRows(list);
        return result;
    }

    /**
     * 不分页查询
     *
     * @param request 不分页查询入参实体类
     * @return 数据库查到的实体类列表
     */
    @Override
    public List<PurchaseOrder> listAllRecord(PurchaseOrder request) {
        //分页处理
        request.setDeleteFlag(0);
        return mapper.selectBySelective(request);
    }

    /**
     * 新增退货单
     *
     * @return
     */
    @Override
    public List<PurchaseContractProductRelResponse> addReturnOrder(PurchaseOrderRequest request) {
        List result = new ArrayList<PurchaseContractProductRelResponse>();
        if (null == request || request.getContractId() == null || request.getContractId() < 1) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "采购单信息不正确");
        }
        //根据合同查询采购单
        PurchaseOrder order = new PurchaseOrder();
        order.setContractId(request.getContractId());
        order.setType(1);
        List<PurchaseOrder> orders = mapper.selectBySelective(order);
        if (CollectionUtil.isEmpty(orders)) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "该合同下暂无对应采购单");
        }
        //查询是否存在退货单
        order.setType(3);
        List<PurchaseOrder> returns = mapper.selectBySelective(order);
        if (CollectionUtil.isEmpty(returns)) {
            PurchaseOrder purchaseOrder = orders.get(0);
            purchaseOrder.setType(3);
            mapper.insert(purchaseOrder);
        }
        //查询合同下所有商品信息
        PurchaseContractProductRel productRel = new PurchaseContractProductRel();
        productRel.setContractCode(request.getContractId());
        List<PurchaseContractProductRel> productRels = productRelMapper.selectBySelective(productRel);
        for (PurchaseContractProductRel rel : productRels) {
            PurchaseContractProductRelResponse response = new PurchaseContractProductRelResponse();
            BeanUtils.copyProperties(rel, response);
            response.setStoreName(orders.get(0).getStoreName());
            result.add(response);
        }
        return result;
    }

    /**
     * 新增补货单
     *
     * @param request
     * @return
     */
    @Override
    public List<PurchaseContractProductRelResponse> addAddOrder(PurchaseOrderRequest request) {
        List result = new ArrayList<PurchaseContractProductRelResponse>();
        if (null == request || request.getContractId() == null || request.getContractId() < 1) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "采购单信息不正确");
        }
        //根据合同查询采购单
        PurchaseOrder order = new PurchaseOrder();
        order.setContractId(request.getContractId());
        order.setType(1);
        List<PurchaseOrder> orders = mapper.selectBySelective(order);
        if (CollectionUtil.isEmpty(orders)) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "该合同下暂无对应采购单");
        }
        //查询是否存在补货单
        order.setType(2);
        List<PurchaseOrder> returns = mapper.selectBySelective(order);
        if (CollectionUtil.isEmpty(returns)) {
            PurchaseOrder purchaseOrder = orders.get(0);
            purchaseOrder.setType(2);
            mapper.insert(purchaseOrder);
        }
        //查询合同下所有商品信息
        PurchaseContractProductRel productRel = new PurchaseContractProductRel();
        productRel.setContractCode(request.getContractId());
        List<PurchaseContractProductRel> productRels = productRelMapper.selectBySelective(productRel);
        for (PurchaseContractProductRel rel : productRels) {
            PurchaseContractProductRelResponse response = new PurchaseContractProductRelResponse();
            BeanUtils.copyProperties(rel, response);
            response.setStoreName(orders.get(0).getStoreName());
            result.add(response);
        }
        return result;
    }

    /**
     * 保存或更新无采购单信息
     *
     * @param request
     * @return
     */
    @Override
    public long updateNoPurchase(PurchaseOrderRequest request) {
        if (request == null) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "采购单信息不能为空");
        }
        if (null == request.getId()) {//新增
            //保存采购单
            PurchaseOrder purchaseOrder = new PurchaseOrder();
            BeanUtils.copyProperties(request, purchaseOrder);
            purchaseOrder.setCode(RandomUtil.randomString(10));
            purchaseOrder.setType(4);
            purchaseOrder.setDeleteFlag(0);
            purchaseOrder.setName("测试无采购收货单");
            purchaseOrder.setStatus(5);
            purchaseOrder.setSupplierName("可口可乐供应商");
            purchaseOrder.setSupplierId("S0001");
            mapper.insert(purchaseOrder);
            //保存商品信息
            String produts = request.getProducts();
            if (StringUtils.isEmpty(produts)) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "采购商品信息不能为空");
            }
            List<PurchaseContractProductRel> list = JSONArray.parseArray(produts, PurchaseContractProductRel.class);
            list.forEach(item -> {
                        item.setPurchaseCode(purchaseOrder.getCode());
                        item.setDeleteFlag(0);
                        productRelMapper.insert(item);
                    }
            );
        } else {
            //修改商品信息
            if (StringUtils.isEmpty(request.getProducts())) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "采购商品信息不能为空");
            }
            List<PurchaseContractProductRel> list = JSONArray.parseArray(request.getProducts(), PurchaseContractProductRel.class);
            list.forEach(item -> {
                        if (null == item.getId()) {
                            item.setPurchaseCode(request.getCode());
                            item.setDeleteFlag(0);
                            productRelMapper.insert(item);
                        } else {
                            productRelMapper.updateByPrimaryKey(item);
                        }
                    }
            );
        }

        return 0;
    }

    @Override
    public Long savePurchaseOrderInfo(PurchaseOrder request) {
        int flag = mapper.insert(request);
        return request.getId();
    }

    @Override
    public Long updatePurchaseOrderInfo(PurchaseOrder request) {
        int flag = mapper.updateByPrimaryKey(request);
        return request.getId();
    }

    @Override
    public int addContractIdInPurchaseOrderInfo(PurchaseOrder request) {
        if (!StringUtils.isNotEmpty(request.getContractCode())){
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "合同编号不正确");
        }
        PurchaseContract contract = new PurchaseContract();
        contract.setCode(Long.valueOf(request.getContractCode()));
        List<PurchaseContract> contracts = purchaseContractMapper.selectBySelective(contract);
        if (null == contracts) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "合同不存在");
        }
        PurchaseOrder purchaseOrder = new PurchaseOrder();
        purchaseOrder.setContractId(contracts.get(0).getId());
        purchaseOrder.setId(request.getId());
        return mapper.updateByPrimaryKey(purchaseOrder);

    }

    @Autowired
    public void setMapper(PurchaseOrderMapper mapper) {
        this.mapper = mapper;
    }
    @Autowired
    public void setPurchaseContractMapper(PurchaseContractMapper purchaseContractMapper) {
        this.purchaseContractMapper = purchaseContractMapper;
    }
    @Autowired
    public void setmStoreApi(MStoreApi mStoreApi) {
        this.mStoreApi = mStoreApi;
    }
    @Autowired
    public void setProductRelMapper(PurchaseContractProductRelMapper productRelMapper) {
        this.productRelMapper = productRelMapper;
    }
}
